import { ExpressMiddlewareInterface, Middleware } from 'routing-controllers';
import {
    USER_AGENT, X_BIZCTX_DOMAIN, X_BIZCTX_LANGUAGE, X_BIZCTX_LAYOUT,
    X_BIZCTX_CC, X_BIZCTX_COUNTRY, X_BIZCTX_STATE, X_BIZCTX_CITY,
    USER_HEADERS, USER_COOKIE, ORIGINAL_URL, X_BIZCTX_CURRENCY, X_BIZCTX_UID
} from 'config/const';
import Container, { Service } from 'typedi';

@Middleware({ type: 'before' })
@Service()
export class LoggingMiddleware implements ExpressMiddlewareInterface {
    use(request: any, response: any, next: (err?: any) => any) {
        if (process.env.NODE_ENV === 'development') {
            response.header('Access-Control-Allow-Origin', '*');
            response.header('Access-Control-Allow-Headers', '*' );
            response.header('Access-Control-Allow-Methods', '*');
            if (request.method.toLowerCase() === 'options') {
                next();
                return;
            }
        }

        // chrome://inspect 模式会出现报错
        if (request.originalUrl === '/json' || request.originalUrl === '/json/version') next();
        else {
            Container.set(X_BIZCTX_DOMAIN, request.headers['x-bizctx-domain']);
            Container.set(X_BIZCTX_LANGUAGE, request.headers['x-bizctx-language']);
            Container.set(X_BIZCTX_LAYOUT, request.headers['x-bizctx-layout']);
            Container.set(X_BIZCTX_CC, request.headers['x-bizctx-cc']);
            Container.set(X_BIZCTX_COUNTRY, request.headers['x-bizctx-country']);
            Container.set(X_BIZCTX_STATE, request.headers['x-bizctx-state']);
            Container.set(X_BIZCTX_CITY, request.headers['x-bizctx-city']);
            Container.set(X_BIZCTX_UID, request.headers['x-bizctx-uid']);
            Container.set(USER_AGENT, request.headers['user-agent']);
            Container.set(USER_HEADERS, request.headers);
            Container.set(ORIGINAL_URL, request.originalUrl);
            Container.set(USER_COOKIE, request.headers.cookie);
            Container.set(X_BIZCTX_CURRENCY, request.headers['x-bizctx-currency']);

            next();
        }
    }
}
